package com.basker.pisces.springcloud.consul;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.core.env.Environment;

/**
 * 往Consul注册服务的时候，默认的instanceId生成规则在集群环境下是有问题的，需要重新设置，
 * 改默认规则为{@value #DEFAULT_CONSUL_INSTANCE_ID}
 *
 * @author hangwen
 */
public class ConsulDiscoveryPropertiesPostProcessor implements BeanPostProcessor {

    public static final String DEFAULT_CONSUL_INSTANCE_ID = "${spring.application.name}:${spring.cloud.client" +
            ".hostname}:${server.port:8080}";
    private static final String CONSUL_DISCOVERY_PROPERTIES_BEAN_NAME = "consulDiscoveryProperties";

    @Autowired
    private Environment environment;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (!CONSUL_DISCOVERY_PROPERTIES_BEAN_NAME.equals(beanName)) {
            return bean;
        }

        if (bean instanceof ConsulDiscoveryProperties) {
            ConsulDiscoveryProperties properties = (ConsulDiscoveryProperties) bean;
            String instanceId = properties.getInstanceId();

            if (StringUtils.isEmpty(instanceId)) {
                instanceId = environment.resolvePlaceholders(DEFAULT_CONSUL_INSTANCE_ID);
                properties.setInstanceId(instanceId);
            }
        }

        return bean;

    }
}
